﻿using AssetManegement.Filter;
using Common;
using IService;
using Microsoft.AspNetCore.Mvc;
using Model.Models;
using ModelDto;
using ModelDto.Request;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace AssetManegement.Controllers
{
    /// <summary>
    /// 系统接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [ServiceFilter(typeof(MyTokenFilterAttribute))]
    public class SysController : ControllerBase
    {
        private readonly ILogger<SysController> _logger;

        private readonly IMenuService _MenuService;
        private readonly IRoleService _RoleService;
        private readonly IAccountService _AccountService;
        private readonly IAccountRoleService _AccountRoleService;
        private readonly IRoleMenuActionService _RoleMenuActionService;

        private readonly ILogService _logService;
        private readonly ICodeCreateTableService _codeCreateTableService;




        public SysController(
            ILogger<SysController> logger,
            IMenuService MenuService,
            IRoleService roleService,
            IAccountService AccountService,
            IAccountRoleService AccountRoleService,
            IRoleMenuActionService RoleMenuActionService,
            ILogService logService,
            ICodeCreateTableService codeCreateTableService
            )
        {
            _logService = logService;
            _logger = logger;
            _MenuService = MenuService;
            _RoleService = roleService;
            _AccountService = AccountService;
            _AccountRoleService = AccountRoleService;
            _RoleMenuActionService = RoleMenuActionService;
            _codeCreateTableService = codeCreateTableService;
        }



        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResultL UploadFile()
        {
            DateTime now = DateTime.Now;
            JsonResultL response = new JsonResultL();



            //后缀名
            string extension = ",.txt,.rar,.zip,.jpg,.jpeg,.gif,.png,.swf,.wmv,.avi,.wma,.mp3,.xls,.xlsx,";

            var currentFile = HttpContext.Request.Form.Files[0];
            //var currentFile = HttpContext.Request.Form.Files.GetFile("file");
            if (currentFile == null)
            {
                return response.Fail("file文件未找到");
            }

            var CurrentExtension = Path.GetExtension(currentFile.FileName);
            if (extension.IndexOf($",{CurrentExtension},") < 0)
            {
                return response.Fail($"格式必须为：{extension}");
            }


            string path = $"{AppContext.BaseDirectory}wwwroot\\FileUrl\\Admin";

            Random rd = new Random();

            var temprd = rd.Next(10000, 99999);

            string pathFile = $"{now.ToString("yyyyMMddHHmmss")}{temprd}{CurrentExtension}";

            string resPath = $"/FileUrl/Admin/{pathFile}";

            var filePath = Path.Combine(path, pathFile);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (var stream = System.IO.File.Create(filePath))
            {
                currentFile.CopyTo(stream);
            };

            _logger.LogInformation($"返回路径：{resPath},保存路径：{filePath}");
            return response.Sucess(resPath);
        }

        #region 菜单

        /// <summary>
        /// 用户 获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetMenuList()
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }


            List<MenuResponse> menus = new List<MenuResponse>();

            if (CurrentUser.Account.IsSysTem == 1)
            {

                //系统管理员 查询所有菜单
                var menuList = await _MenuService.GetListCacheAsync();

                menuList =menuList.Where(a => a.EnableState == 1).ToList();

                if (menuList != null && menuList.Count > 0)
                {
                    foreach (var item in menuList)
                    {
                        menus.Add(EntityMapperHelper.Mapper<MenuResponse, Menu>(item));
                    }

                }

            }
            else
            {
                menus = await _MenuService.GetMenusByUserId(CurrentUser.Account.Id);
            }
            menus = menus.OrderBy(a => a.Sort).ToList();
            return response.Sucess(menus);
        }

        /// <summary>
        /// 权限 获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetMenuPowerList()
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }


            List<MenuResponse> menus = new List<MenuResponse>();

            if (CurrentUser.Account.IsSysTem == 1)
            {

                //系统管理员 查询所有菜单
                var menuList = await _MenuService.GetListCacheAsync();

                if (menuList != null && menuList.Count > 0)
                {

                    foreach (var item in menuList)
                    {
                        menus.Add(EntityMapperHelper.Mapper<MenuResponse, Menu>(item));
                    }

                }

            }
            else
            {
                menus = await _MenuService.GetMenusByUserId(CurrentUser.Account.Id);
            }
            menus = menus.OrderBy(a => a.Sort).ToList();
            return response.Sucess(menus);
        }
        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetMenuTreeList()
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }


            List<MenuResponse> menus = new List<MenuResponse>();

            //系统管理员 查询所有菜单
            var menuList = await _MenuService.GetListCacheAsync();

            if (menuList != null && menuList.Count > 0)
            {
                foreach (var item in menuList)
                {
                    menus.Add(EntityMapperHelper.Mapper<MenuResponse, Menu>(item));
                }
            }

            var lisst1 = menus.Where(a => a.Level == 1).OrderBy(a => a.Sort).ToList();
            var lisst2 = menus.Where(a => a.Level == 2).ToList();

            List<MenuResponse> menusRes = new List<MenuResponse>();

            foreach (var item in lisst1)
            {
                menusRes.Add(item);

                var itemNext = lisst2.Where(a => a.ParentId == item.Id).OrderBy(a => a.Sort).ToList();

                menusRes.AddRange(itemNext);
            }
            return response.Sucess(menusRes);
        }


        /// <summary>
        /// 菜单 - 新增 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> SaveMenu(MenuRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            if (request.Code.Contains(","))
            {
                return response.Fail("菜单Code不能包含英文逗号");
            }

            if (string.IsNullOrWhiteSpace(request.Id))
            {
                //新增
                Menu entity = await _MenuService.QueryAsync(a => a.MenuName == request.MenuName);
                if (entity != null)
                {
                    return response.Fail("菜单名称已存在");
                }

                entity = new Menu();

                entity.ParentId = request.ParentId;
                entity.Level = request.Level;

                entity.LinkUrl = request.LinkUrl;
                entity.Code = request.Code;
                entity.Sort = request.Sort;
                entity.MenuName = request.MenuName;
                if (entity.Level == 1)
                {
                    entity.LinkUrl = "";
                    entity.ParentId = "";
                }
                else
                {
                    //查找上级菜单
                    Menu parentMenu = await _MenuService.FindAsync(request.ParentId);
                    if (parentMenu == null)
                    {
                        return response.Fail("父级菜单异常");
                    }
                    entity.Code = $"{parentMenu.Code}.{request.Code}";

                }

                Menu entityPower = await _MenuService.QueryAsync(a => a.Code == entity.Code);
                if (entityPower != null)
                {
                    return response.Fail("菜单code已存在");
                }

                entity.EnableState = 1;

                entity.Id = Guid.NewGuid().ToString("N");
                entity.IsDelete = false;
                entity.CreateTime = now;
                entity.CreateUser = CurrentUser.Account.Id;
                entity.UpdateUser = "";
                entity.DeleteUser = "";
                entity.Remark = "";

                bool flag = await _MenuService.AddAsync(entity);

                return flag ? response.Sucess("新增成功") : response.Fail("新增失败");
            }
            else
            {
                //修改
                Menu entity = await _MenuService.QueryAsync(a => a.MenuName == request.MenuName && a.Id != request.Id);
                if (entity != null)
                {
                    return response.Fail("菜单名称已存在");
                }

                Menu ediEntity = await _MenuService.FindAsync(request.Id);
                if (ediEntity == null)
                {
                    return response.Fail("菜单名称已存在");
                }


                ediEntity.LinkUrl = request.LinkUrl;
                ediEntity.Icon = request.Icon;
                ediEntity.MenuName = request.MenuName;
                ediEntity.Code = request.Code;
                ediEntity.ParentId = request.ParentId;
                ediEntity.Sort = request.Sort;

                ediEntity.UpdateUser = CurrentUser.Account.Id;
                ediEntity.UpdateTime = now;

                if (ediEntity.Level == 2)
                {
                    //查找上级菜单
                    Menu parentMenu = await _MenuService.FindAsync(ediEntity.ParentId);
                    if (parentMenu == null)
                    {
                        return response.Fail("父级菜单异常");
                    }

                    if (ediEntity.Code.IndexOf(parentMenu.Code) == 0)
                    {

                    }
                    else
                    {
                        ediEntity.Code = $"{parentMenu.Code}.{ediEntity.Code}";
                    }
                    Menu entityPower = await _MenuService.QueryAsync(a => a.Code == ediEntity.Code && a.Id != ediEntity.Id);
                    if (entityPower != null)
                    {
                        return response.Fail("菜单code已存在");
                    }

                }


                bool flag = await _MenuService.UpdateAsync(ediEntity);

                return flag ? response.Sucess("修改成功") : response.Fail("修改失败");
            }


        }


        /// <summary>
        /// 菜单 - 启用 禁用
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> Enable(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }




            if (string.IsNullOrWhiteSpace(request.Id))
            {
                return response.Fail("参数错误");
            }

            var model = await _MenuService.FindAsync(request.Id);
            if (model == null)
            {
                return response.Fail("数据异常");
            }

            model.EnableState = model.EnableState == 1 ? 2 : 1;
            model.UpdateTime = now;
            model.UpdateUser = CurrentUser.Account.Id;

            var flag = await _MenuService.UpdateAsync(model);


            return flag ? response.Sucess("操作成功") : response.Fail("操作失败");

        }



        /// <summary>
        /// 菜单-删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> Delete(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }



            if (string.IsNullOrWhiteSpace(request.Id))
            {
                return response.Fail("参数错误");
            }

            var jingqu = await _MenuService.FindAsync(request.Id);
            if (jingqu == null)
            {
                return response.Fail("数据异常");
            }

            jingqu.IsDelete = true;
            jingqu.DeleteTime = now;
            jingqu.DeleteUser = CurrentUser.Account.Id;

            var flag =await _MenuService.UpdateAsync(jingqu);


            return flag ? response.Sucess("删除成功") : response.Fail("删除失败");
        }
        #endregion

        #region 角色

        /// <summary>
        /// 获取角色列表-全部
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetRoleListAll()
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            List<RoleResponse> list = new List<RoleResponse>();
            var resList =await _RoleService.GetListCacheAsync();

            resList = resList.OrderBy(a => a.Sort).ToList();

            if (resList != null && resList.Count > 0)
            {
                foreach (var item in resList)
                {
                    list.Add(EntityMapperHelper.Mapper<RoleResponse, Role>(item));
                }
            }

            return response.Sucess(list);
        }

        /// <summary>
        /// 获取角色列表-根据用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetRoleListByUser(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();
            List<RoleResponse> list = new List<RoleResponse>();
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            var AccountRoleList =await _AccountRoleService.GetListCacheAsync();

            AccountRoleList = AccountRoleList.Where(a => a.AccountId == request.Id).ToList();

            if (AccountRoleList == null || AccountRoleList.Count == 0)
            {
                return response.Sucess(list);
            }

            var roleids = AccountRoleList.Select(a => a.RoleId).Distinct().ToList();
            var resList =await _RoleService.GetListCacheAsync();

            resList = resList.Where(a => roleids.Contains(a.Id)).ToList();

            resList = resList.OrderBy(a => a.Sort).ToList();

            if (resList != null && resList.Count > 0)
            {
                foreach (var item in resList)
                {
                    list.Add(EntityMapperHelper.Mapper<RoleResponse, Role>(item));
                }
            }

            return response.Sucess(list);
        }


        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetRoleList(RoleRequestPage request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            List<RoleResponse> list = new List<RoleResponse>();
            var resList = await _RoleService.GetListCacheAsync();

            if (!string.IsNullOrWhiteSpace(request.KeyWords))
            {
                resList = resList.Where(a => a.RoleName.Contains(request.KeyWords)).ToList();
            }

            int count = resList.Count();
            if (request.PageIndex <= 1)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize < 1)
            {
                request.PageSize = 10;
            }

            resList =  resList.OrderBy(a => a.Sort).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            if (resList != null && resList.Count > 0)
            {
                var accountRoles = await _AccountRoleService.GetListCacheAsync();

                var userIds = accountRoles.Select(a => a.AccountId).Distinct().ToList();

                var userList = await _AccountService.QueryListAsync(a => userIds.Contains(a.Id));


                foreach (var item in resList)
                {
                    var temp = EntityMapperHelper.Mapper<RoleResponse, Role>(item);

                    var accountIdList =  accountRoles.Where(a => a.RoleId == item.Id).Select(a => a.AccountId).Distinct().ToList();

                    temp.PersonList = "";

                    if (accountIdList != null && accountIdList.Count > 0)
                    {
                        foreach (var uid in accountIdList)
                        {
                            var u = userList.FirstOrDefault(a => a.Id == uid);
                            temp.PersonList += $"{u?.Name ?? ""},";
                        }
                    }

                    list.Add(temp);
                }
            }


            return response.Sucess(new { list = list, total = count });
        }

        /// <summary>
        /// 角色 - 新增 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> SaveRole(RoleRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }



            if (string.IsNullOrWhiteSpace(request.Id))
            {
                //新增
                var entity = await _RoleService.QueryAsync(a => a.RoleName == request.RoleName);
                if (entity != null)
                {
                    return response.Fail("名称已存在");
                }



                entity = new Role();

                entity.RoleName = request.RoleName;
                entity.Remark = request.Remark;
                entity.Sort = request.Sort;


                entity.CreateTime = now;
                entity.CreateUser = CurrentUser.Account.Id;


                bool flag = await _RoleService.AddAsync(entity);

                return flag ? response.Sucess("新增成功") : response.Fail("新增失败");
            }
            else
            {
                if (request.Id == "xitongguanliyuanrole")
                {
                    return response.Fail("当前项不可修改");
                }
                //修改
                var entity = await _RoleService.QueryAsync(a => a.RoleName == request.RoleName && a.Id != request.Id);
                if (entity != null)
                {
                    return response.Fail("名称已存在");
                }

                entity = await _RoleService.FindAsync(request.Id);
                if (entity == null)
                {
                    return response.Fail("数据异常");
                }


                entity.Remark = request.Remark;
                entity.RoleName = request.RoleName;
                entity.Sort = request.Sort;

                entity.UpdateUser = CurrentUser.Account.Id;
                entity.UpdateTime = now;



                bool flag = await _RoleService.UpdateAsync(entity);

                return flag ? response.Sucess("修改成功") : response.Fail("修改失败");
            }


        }

        /// <summary>
        /// 角色-删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> DeleteRole(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }
            if (string.IsNullOrWhiteSpace(request.Id))
            {
                return response.Fail("参数错误");
            }
            if (request.Id == "xitongguanliyuanrole")
            {
                return response.Fail("当前项不可删除");
            }


            var entity = _RoleService.Find(request.Id);
            if (entity == null)
            {
                return response.Fail("数据异常");
            }


            var flag = await _AccountRoleService.DelleteRole(request.Id, CurrentUser.Account.Id);


            return flag ? response.Sucess("删除成功") : response.Fail("删除失败");
        }
        #endregion


        #region 用户

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetAccountList(AccountRequestPage request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            List<AccountResponse> list = new List<AccountResponse>();
            var resList = await _AccountService.GetListCacheAsync();
            resList = resList.Where(a => a.Id != "xitongguanliyuan").ToList();
            if (!string.IsNullOrWhiteSpace(request.KeyWords))
            {
                resList = resList.Where(a => a.Name.Contains(request.KeyWords) || a.AccountNo.Contains(request.KeyWords)).ToList();
            }
            if (!string.IsNullOrWhiteSpace(request.RoleId))
            {
                var accountIdsList = await _AccountRoleService.GetListCacheAsync();

                var accountIds = accountIdsList.Where(a => a.RoleId == request.RoleId).Select(a => a.AccountId).ToList();

                resList = resList.Where(a => accountIds.Contains(a.Id)).ToList();
            }
            int count = resList.Count();
            if (request.PageIndex <= 1)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize < 1)
            {
                request.PageSize = 10;
            }

            resList = resList.OrderBy(a => a.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            if (resList != null && resList.Count > 0)
            {
                foreach (var item in resList)
                {
                    list.Add(EntityMapperHelper.Mapper<AccountResponse, Account>(item));
                }
            }


            return response.Sucess(new { list = list, total = count });
        }

        /// <summary>
        /// 获取用户列表 - 通过角色ID 不分页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetAccountListByRoleId(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            List<AccountResponse> list = new List<AccountResponse>();
            var resList =await _AccountService.GetListCacheAsync();


            var accountIdsList = await _AccountRoleService.GetListCacheAsync();

            var accountIds = accountIdsList.Where(a => a.RoleId == request.Id).Select(a => a.AccountId).ToList();

            resList = resList.Where(a => accountIds.Contains(a.Id)).OrderBy(a => a.Name).ToList();

            if (resList != null && resList.Count > 0)
            {
                foreach (var item in resList)
                {
                    item.Pwd = "";//密码不给
                    list.Add(EntityMapperHelper.Mapper<AccountResponse, Account>(item));
                }
            }


            return response.Sucess(list);
        }



        /// <summary>
        /// 用户 - 新增 修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> SaveAccount(AccountRequestWeb request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            (bool flag, string msg) = await _AccountService.SaveAccount(request, CurrentUser.Account);

            return flag ? response.Sucess("操作成功") : response.Fail(msg);



        }

        /// <summary>
        /// 用户-删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> DeleteAccount(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }
            if (string.IsNullOrWhiteSpace(request.Id))
            {
                return response.Fail("参数错误");
            }

            if (request.Id == "xitongguanliyuan")
            {
                return response.Fail("系统账户不让删除");
            }
            var entity = await _AccountService.FindAsync(request.Id);
            if (entity == null)
            {
                return response.Fail("数据异常");
            }

            //if (entity.IsSysTem==1)
            //{
            //    return response.Fail("系统账户不让删除");
            //}

            entity.IsDelete = true;
            entity.DeleteTime = now;
            entity.DeleteUser = CurrentUser.Account.Id;

            var flag =await _AccountService.UpdateAsync(entity);


            return flag ? response.Sucess("删除成功") : response.Fail("删除失败");
        }


        /// <summary>
        /// 账户 - 启用 禁用
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> EnableAccount(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }




            if (string.IsNullOrWhiteSpace(request.Id))
            {
                return response.Fail("参数错误");
            }

            if (request.Id == "xitongguanliyuan")
            {
                return response.Fail("系统账户不可操作");
            }

            var model =await _AccountService.FindAsync(request.Id);
            if (model == null)
            {
                return response.Fail("数据异常");
            }

            model.EnableState = model.EnableState == 1 ? 2 : 1;
            model.UpdateTime = now;
            model.UpdateUser = CurrentUser.Account.Id;

            var flag =await _AccountService.UpdateAsync(model);


            return flag ? response.Sucess("操作成功") : response.Fail("操作失败");

        }


        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> ResetPassword(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }


            if (string.IsNullOrWhiteSpace(request.Id))
            {
                return response.Fail("参数错误");
            }


            var model = await _AccountService.FindAsync(request.Id);
            if (model == null)
            {
                return response.Fail("数据异常");
            }


            model.Pwd = MD5Helper.Md5Encrypt("123456");

            model.UpdateTime = now;
            model.UpdateUser = CurrentUser.Account.Id;

            var flag = await _AccountService.UpdateAsync(model);


            return flag ? response.Sucess("重置密码成功：123456") : response.Fail("重置密码失败");

        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> UpdatePwd(AccountUpdatePwdRequest request)
        {

            JsonResultL response = new JsonResultL();
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }


            var account = await _AccountService.FindAsync(CurrentUser.Account.Id);
            if (account == null)
            {
                return response.Fail("用户异常");
            }

            string tempPwd = MD5Helper.Md5Encrypt(request.Pwd);

            if (string.IsNullOrWhiteSpace(request.Pwd) || request.PwdNew.Length > 20 || request.PwdNew.Length < 6)
            {
                return response.Fail("新密码在6-20位之间");
            }
            if (tempPwd != account.Pwd)
            {
                return response.Fail("原密码错误");
            }

            account.Pwd = MD5Helper.Md5Encrypt(request.PwdNew);

            account.UpdateTime = DateTime.Now;

            bool flag = await _AccountService.UpdateAsync(account);

            return flag ? response.Sucess("密码修改成功") : response.Fail("密码修改失败");
        }


        #endregion

        #region 权限

        /// <summary>
        /// 获取角色权限
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetRolePower(DeleteRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            List<RoleMenuActionResponse> list = new List<RoleMenuActionResponse>();
            var resList = await _RoleMenuActionService.GetListCacheAsync();
            resList = resList.Where(a => a.RooleId == request.Id).ToList();


            if (resList != null && resList.Count > 0)
            {
                foreach (var item in resList)
                {
                    list.Add(EntityMapperHelper.Mapper<RoleMenuActionResponse, RoleMenuAction>(item));
                }
            }

            return response.Sucess(list);
        }

        /// <summary>
        /// 权限保存
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> SaveRolePower(List<RoleMenuActionRequest> list)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            var roleIds = list.Select(a => a.RooleId).Distinct().ToList();


            var menuIds = list.Select(a => a.MenuId).Distinct().ToList();


            var currentRoleList = await _RoleService.GetListCacheAsync();
            var currentRole = currentRoleList.Where(a => roleIds.Contains(a.Id)).FirstOrDefault();

            if (currentRole == null)
            {
                return response.Fail("角色异常");
            }

            var menuList =await _MenuService.GetListCacheAsync();
            menuList = menuList.Where(a => menuIds.Contains(a.Id)).ToList();

            if (menuList.Count != menuIds.Count)
            {
                return response.Fail("菜单异常");
            }

            List<RoleMenu> roleMenus = new List<RoleMenu>();
            List<RoleMenuAction> roleMenuActions = new List<RoleMenuAction>();

            foreach (var item in list)
            {
                //当前菜单
                var currentMenu = menuList.FirstOrDefault(a => a.Id == item.MenuId);


                RoleMenu roleMenu = new RoleMenu()
                {
                    RoleId = currentRole.Id,
                    MenuId = item.MenuId
                };

                roleMenus.Add(roleMenu);
                if (currentMenu.Level == 2)
                {
                    var currentCount = roleMenus.Where(a => a.MenuId == item.MenuId).Count();
                    if (currentCount == 0)
                    {
                        RoleMenu roleMenu2 = new RoleMenu()
                        {
                            RoleId = currentRole.Id,
                            MenuId = item.MenuId
                        };

                        roleMenus.Add(roleMenu2);
                    }

                    RoleMenuAction roleMenuAction = new RoleMenuAction()
                    {
                        MenuId = item.MenuId,
                        RooleId = currentRole.Id,
                        MenuActionId = item.MenuActionId
                    };

                    roleMenuActions.Add(roleMenuAction);
                }

            }

            bool flag =await _RoleMenuActionService.SetPower(roleMenus, roleMenuActions, CurrentUser.Account, currentRole.Id);


            return flag ? response.Sucess("保存成功") : response.Fail("保存失败");

        }
        /// <summary>
        /// 权限保存
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> SaveRolePowerV3(RoleMenuActionRequestV3 request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            var currentRoleList = await _RoleService.GetListCacheAsync();
            var currentRole = currentRoleList.Where(a => a.Id == request.RoleId).FirstOrDefault();
            if (currentRole == null)
            {
                return response.Fail("角色异常");
            }



            var menuIds = request.PowerList.Select(a => a.MenuId).Distinct().ToList();
            var menuList = await _MenuService.GetListCacheAsync();

            if (menuIds !=null && menuIds.Any())
            {
                menuList = menuList.Where(a => menuIds.Contains(a.Id)).ToList();

                if (menuList.Count != menuIds.Count)
                {
                    return response.Fail("菜单异常");
                }
            }

          
            List<RoleMenu> roleMenus = new List<RoleMenu>();
            List<RoleMenuAction> roleMenuActions = new List<RoleMenuAction>();

            foreach (var item in request.PowerList)
            {
                //当前菜单
                var currentMenu = menuList.FirstOrDefault(a => a.Id == item.MenuId);


                RoleMenu roleMenu = new RoleMenu()
                {
                    RoleId = currentRole.Id,
                    MenuId = item.MenuId
                };

                roleMenus.Add(roleMenu);
                if (currentMenu.Level == 2)
                {
                    var currentCount = roleMenus.Where(a => a.MenuId == item.MenuId).Count();
                    if (currentCount == 0)
                    {
                        RoleMenu roleMenu2 = new RoleMenu()
                        {
                            RoleId = currentRole.Id,
                            MenuId = item.MenuId
                        };

                        roleMenus.Add(roleMenu2);
                    }

                    RoleMenuAction roleMenuAction = new RoleMenuAction()
                    {
                        MenuId = item.MenuId,
                        RooleId = currentRole.Id,
                        MenuActionId = item.MenuActionId
                    };

                    roleMenuActions.Add(roleMenuAction);
                }

            }

            bool flag = await _RoleMenuActionService.SetPower(roleMenus, roleMenuActions, CurrentUser.Account, currentRole.Id);


            return flag ? response.Sucess("保存成功") : response.Fail("保存失败");

        }

        /// <summary>
        /// 角色-成员保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> SaveRolePowerV2(RoleUserListRequest request)
        {
            JsonResultL response = new JsonResultL();
            DateTime now = DateTime.Now;
            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }
            var userIDs = request.PersonList.Select(a => a.Id).Distinct().ToList();



            var currentRole = _RoleService.Find(request.Id);

            if (currentRole == null)
            {
                return response.Fail("角色异常");
            }


            var flag =await _AccountRoleService.SaveRoleUser(request.Id, userIDs, CurrentUser.Account.Id);


            return flag ? response.Sucess("保存成功") : response.Fail("保存失败");

        }





        #endregion




        #region 获取日志列表

        /// <summary>
        /// GetLoginLogList日志
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetLoginLogList(LogRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            if (CurrentUser.Account.IsSysTem != 1)
            {
                return response.Fail("非系统超级管理员无权限使用此功能");
            }

            (var list, int count) = await _logService.GetLoginLogList(request);


            return response.Sucess(new { list = list, total = count });
        }
        /// <summary>
        /// GetErrorLogList日志
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetErrorLogList(LogRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            if (CurrentUser.Account.IsSysTem != 1)
            {
                return response.Fail("非系统超级管理员无权限使用此功能");
            }

            (var list, int count) = await _logService.GetErrorLogList(request);


            return response.Sucess(new { list = list, total = count });
        }
        /// <summary>
        /// GetApiLogList日志
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetApiLogList(LogRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            if (CurrentUser.Account.IsSysTem != 1)
            {
                return response.Fail("非系统超级管理员无权限使用此功能");
            }

            (var list, int count) = await _logService.GetApiLogList(request);

            return response.Sucess(new { list = list, total = count });
        }

        #endregion

        #region 获取需要生成前端代码 表集合

        /// <summary>
        /// GetLoginLogList日志
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> GetCodeCreateList(KeyWordsRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            if (CurrentUser.Account.IsSysTem != 1)
            {
                return response.Fail("非系统超级管理员无权限使用此功能");
            }

            var list = await _codeCreateTableService.GetList(request.KeyWords);


            return response.Sucess(list);
        }

        /// <summary>
        /// GetLoginLogList生成代码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResultL> CodeCreate(PageBaseRequest request)
        {
            JsonResultL response = new JsonResultL();

            string tempUser = HttpContext.Request.Headers["LUserInfo"].ToString();
            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tempUser);

            if (CurrentUser == null || CurrentUser.Account == null)
            {
                return response.TokenFail("用户异常");
            }

            if (CurrentUser.Account.IsSysTem != 1)
            {
                return response.Fail("非系统超级管理员无权限使用此功能");
            }

            var res = _codeCreateTableService.CodeCreate(request.KeyWords);


            return response.Sucess(res);
        }

        #endregion
    }
}
